#include "mapwindow.h"
#include "ui_mapwindow.h"
#include <QFile>
#include <QDebug>
#include <QPixmap>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMessageBox>
#include <QMouseEvent>
#include <cmath>

MapWindow::MapWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MapWindow)
{
    ui->setupUi(this);
    this->manager=new QNetworkAccessManager;

    this->mapDragEvent = new MapDragEvent(this);
    this->installEventFilter(this->mapDragEvent); // 安装事件过滤器

    connect(mapDragEvent,&MapDragEvent::mapPositionChanged,this,&MapWindow::updateMapPosition);
}

MapWindow::~MapWindow()
{
    delete ui;
}

void MapWindow::initMap()
{
    //发起请求
    QString url=QString(MAP_API)
            .arg(MAP_AK)
            .arg(MAP_WIDTH)
            .arg(MAP_HEIGHT)
            .arg(this->lng)
            .arg(this->lat)
            .arg(this->zoom);
    manager->get(QNetworkRequest(QUrl(url)));
    connect(manager,&QNetworkAccessManager::finished,this,&MapWindow::showMap);
}

void MapWindow::getPublicIPAddress()
{
    QNetworkAccessManager *ipManager = new QNetworkAccessManager();
        QUrl url("http://ipinfo.io/ip");
        QNetworkReply *reply = ipManager->get(QNetworkRequest(url));
        QObject::connect(reply, &QNetworkReply::finished, [ipManager,reply,this]() {
            if (reply->error() == QNetworkReply::NoError) {
                QString ipAddress = QString(reply->readAll());
                this->ip = ipAddress;
            } else {
                qDebug() << "Error:" << reply->errorString();
            }
            reply->deleteLater();
            delete ipManager;

            // 应该确保上一步的数据拿到以后，再去执行下一步
            this->getPublicLngLat();
        });
}

void MapWindow::getPublicLngLat()
{
    QNetworkAccessManager *addressManager = new QNetworkAccessManager();
       QString url = QString(MAP_LNGLAT).arg(MAP_AK).arg(this->ip);
       QNetworkReply *reply = addressManager->get(QNetworkRequest(QUrl(url)));
       // 这个地方就是在绑定信号槽，获取返回结果
       QObject::connect(reply, &QNetworkReply::finished, [addressManager,reply,this]() {
           // 解析json格式字符串，获取经纬度
           QByteArray data = reply->readAll();
           //qDebug() << "获取经纬度" << data;
           QJsonDocument doc = QJsonDocument::fromJson(data);
           QJsonObject obj = doc.object();
           QJsonObject content = obj.value("content").toObject();
           QJsonObject point = content.value("point").toObject();
           // 获取经纬度设置给this
           this->lng = point.value("x").toString();
           this->lat = point.value("y").toString();
           //qDebug() << this->lng << "    " << this->lat;

           reply->deleteLater();
           delete addressManager;

           this->initMap();
       });
}

void MapWindow::init()
{
    this->getPublicIPAddress();
}

void MapWindow::on_btn_back_clicked()
{
    this->parentWidget()->show();
    this->hide();
}

void MapWindow::showMap(QNetworkReply *reply)
{
    QFile file("./temp.png");
    if(!file.open(QIODevice::ReadWrite)){
        qDebug()<<"打开失败";
        return;
    }
    file.write(reply->readAll());
    file.close();

    //将图片展示在窗口
    QPixmap map("./temp.png");
    ui->label_map->setPixmap(map);
}


void MapWindow::on_btn_big_clicked()
{
    if(this->zoom==18){
        QMessageBox::about(this,"提示","地图已最大化");
        return;
    }
    this->zoom++;
    this->initMap();
}


void MapWindow::on_btn_small_clicked()
{
    if(this->zoom==3){
        QMessageBox::about(this,"提示","地图已最小化");
        return;
    }
    this->zoom--;
    this->initMap();
}


void MapWindow::updateMapPosition(const QPoint &delta)
{
    // 记录结束经度和纬度
    endLng = lng.toDouble();
    endLat = lat.toDouble();

    // 根据鼠标移动距离计算新的经纬度（反转方向）
    double move_x = endLng - delta.x() * 0.0000003 * pow(19 - zoom, 4);  // 新经度
    double move_y = endLat + delta.y() * 0.0000003 * pow(19 - zoom, 4);  // 新纬度

    // 限制经纬度范围
    // 经度范围：-180 到 180
    // 纬度范围：-90 到 90
    move_x = qBound(-180.0, move_x, 180.0);
    move_y = qBound(-90.0, move_y, 90.0);

    // 更新经纬度
    this->lng = QString::number(move_x);
    this->lat = QString::number(move_y);

    // 重新初始化地图
    this->initMap();
}

// 在鼠标按下事件中记录开始经度和纬度
void MapWindow::mousePressEvent(QMouseEvent *event)
{
    startLng = lng.toDouble();
    startLat = lat.toDouble();
    QMainWindow::mousePressEvent(event);
}
